import { PageHeaderWrapper } from '@ant-design/pro-layout';

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Button,
  Table,
  Icon,
  Divider,
  Popconfirm,
  Spin,
  message,
  Tooltip,
  Form,
  Input,
  Select,
  Card,
} from 'antd';
import MyPageTable from '@/components/MyPageTable';
import { onTableData } from '@/utils/utils.js';
import { router } from 'umi';
const { Option } = Select;
@connect(({ coupons, loading }) => ({
  ...coupons,
  loading: loading.models.coupons,
}))
@Form.create()
class List extends PureComponent {
  state = {
    isFormModal: false,
    isDisabled: false,
    current: 1,
    typeVal: 'SINGLE',  // 用法-随用法select框改变
    typeVal2: 'SINGLE', // 用法-随搜索条件改变
  };
  
  componentWillMount() {
    const { queryInfo } = this.props;
    this.setDispatch({
      type: "SINGLE",
      status: "VALID",
      hasAssign: "false",
    });
  }
  
  setDispatch(data = {}) {
    const { dispatch } = this.props;
    const { current } = this.state;

    if (data.type === 'PACKAGE') {
      data.hasAssign = data.hasAssign === 'true'
                        ? true
                        : data.hasAssign === 'false'
                          ? false
                          : null;
    } else {
      data.hasAssign = '';
    }

    this.setState({
      typeVal2: data.type
    })

    dispatch({
      type: 'coupons/couponTemplatequeryPage',
      payload: {
        pageNumber: current,
        pageSize: 10,
        ...data,
      },
    });
  }
  
  handleDelete = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'coupons/deleteList',
      payload: { id },
      callback: res => {
        // this.setDispatch();
        this.handleSubmit();
        message.success('删除成功');
      },
    });
  };
  
  handleAdd = () => {
    router.push('/coupons/list/add');
  };

  typeChange = e => {
    this.setState({
      typeVal: e,
    })
  }
  
  editDetail = record => {
    router.push(`/coupons/list/add?id=${record.id}`);
  };
  onThepage = e => {
    const { dispatch } = this.props;

    props.form.validateFields((err, values) => {
      if (!err) {
        this.setState(
          {
            current: e.current,
          },
          () => {
            dispatch({
              type: 'coupons/couponTemplatequeryPage',
              payload: {
                pageNumber: e.current,
                pageSize: 10,
                type: "SINGLE",
                status: "VALID",
                hasAssign: "false",
                ...values,
                //   sourceShopId: getShopId()
              },
            });
          },
        );
      }
    })
  };
  
  handleSubmit = e => {
    e && e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setDispatch(values);
      }
    });
  };

  // 嵌套的子表格
  expandedRowRender = (data) => {
    data = onTableData(data.history || [])
    const columns = [
      {
        title: ' ',
        dataIndex: 'bindId',
        key:'bindId',
        render: text => <span style={{ display: 'none' }}>{`${text}`}</span>
      },
      {
        title: '版本',
        dataIndex: 'id',
        key:'id'
      },
      {
        title: '名称',
        dataIndex: 'title',
        key:'title'
      },
      {
        title: '发放总量',
        dataIndex: 'num',
        key:'num'
      },
      {
        title: '库存',
        dataIndex: 'leftNum',
        key:'leftNum'
      },
      {
        title: '面额',
        dataIndex: 'discountAmount',
        key:'discountAmount'
      },
      {
        title: '使用条件',
        dataIndex: 'minAmount',
        key:'minAmount',
        render: text => (text === 0 ? `不限制` : `满${text}元使用`),
      },
      {
        title: '每人限领',
        dataIndex: 'userLimitNum',
        key:'userLimitNum',
        render: text => (text === '0' ? '不限' : `${text}张`),
      },
      {
        title: '时间设置',
        dataIndex: 'type',
        key:'type',
        render: (text, record) =>
          record.delayDayNum ? (
            `自领取${record.delayDayNum}天内使用`
          ) : (
            <div>
              <div>开始：{record.startTime}</div>
              <div>结束：{record.endTime}</div>
            </div>
          ),
      },
      {
        title: '是否已分配大礼包',
        colSpan: this.state.typeVal2 === 'PACKAGE' ? 1 : 0,
        dataIndex: 'packageId',
        key:'packageId',
        render: (text, e) => {
          return {
            children: e.packageId ? '是' : '否',
            props: {
              colSpan: this.state.typeVal2 === 'PACKAGE' ? 1 : 0,
            },
          };
        },
      },
      {
        title: '优惠券状态',
        dataIndex: 'status',
        key:'status',
        render: status => (
          <div>
            <span>
              {status === 'VALID'
                ? '有效'
                : status === 'UNASSIGNED'
                ? '未配大礼包'
                : status === 'ASSIGNED'
                ? '已经分配大礼包'
                : status === 'RUN_OUT'
                ? '已经领取完'
                : '无效'}
            </span>
          </div>
        ),
      },
      {
        title: '操作',
        dataIndex: 'action',
        key:'action',
        colSpan: this.state.typeVal2 === 'PACKAGE' ? 1 : 2,
        render: (_, record) => {
          return {
            children: (
              <div style={{ textAlign: 'center' }}>
                <span
                  onClick={() => router.push(`/coupons/ToView?id=${record.id}`)}
                  style={{ cursor: 'pointer', color: '#E83F40' }}
                >
                  查看
                </span>
                {/* <Tooltip title="查看">
                  <span
                    onClick={() => router.push(`/coupons/ToView?id=${record.id}`)}
                    style={{ cursor: 'pointer', color: '#E83F40' }}
                  >
                    查看
                  </span>
                  <Icon
                    type="eye"
                    onClick={() => router.push(`/coupons/ToView?id=${record.id}`)}
                    style={{ cursor: 'pointer', color: '#E83F40' }}
                  />
                </Tooltip> */}
              </div>
            ),
            props: {
              colSpan: this.state.typeVal2 === 'PACKAGE' ? 1 : 2,
            },
          };
        },
      },
    ];

    return <Table showHeader={false} columns={columns} dataSource={data} pagination={false} />;
  };

  // 重置
  handleReset = e => {
    this.props.form.resetFields();

    this.setState({
      typeVal: 'SINGLE',
    })
    this.props.form.setFieldsValue({
      status: undefined,
    });
    this.setDispatch({
      type: "SINGLE",
      // status: "VALID",
      hasAssign: "false",
    });
  };
  
  onCancel = () => {
    this.setState({ isFormModal: false, current: {} });
  };
  
  render() {
    const { list, loading, listData, total } = this.props;
    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: total,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      ),
    };
    const columns = [
      {
        title: '优惠券ID',
        dataIndex: 'bindId',
        key: 'bindId',
      },
      {
        title: '版本',
        dataIndex: 'id',
        key: 'id',
        render: text => <span>{`${text}(最新)`}</span>
      },
      {
        title: '名称',
        dataIndex: 'title',
        key: 'title',
      },
      {
        title: '发放总量',
        key: 'num',
        dataIndex: 'num',
      },
      {
        title: '库存',
        dataIndex: 'leftNum',
        key: 'leftNum',
      },
      {
        title: '面额',
        dataIndex: 'discountAmount',
        key: 'discountAmount',
      },
      {
        title: '使用条件',
        dataIndex: 'minAmount',
        key: 'minAmount',
        render: text => (text === 0 ? `不限制` : `满${text}元使用`),
      },
      {
        title: '每人限领',
        dataIndex: 'userLimitNum',
        key: 'userLimitNum',
        render: text => (text === '0' ? '不限' : `${text}张`),
      },
      {
        title: '时间设置',
        dataIndex: 'type',
        key: 'type',
        render: (text, record) =>
          record.delayDayNum ? (
            `自领取${record.delayDayNum}天内使用`
          ) : (
            <div>
              <div>开始：{record.startTime}</div>
              <div>结束：{record.endTime}</div>
            </div>
          ),
      },
      {
        title: '是否已分配大礼包',
        colSpan: this.state.typeVal2 === 'PACKAGE' ? 1 : 0,
        dataIndex: 'packageId',
        key: 'packageId',
        render: (text, e) => {
          return {
            children: e.packageId ? '是' : '否',
            props: {
              colSpan: this.state.typeVal2 === 'PACKAGE' ? 1 : 0,
            },
          };
        },
      },
      {
        title: '优惠券状态',
        dataIndex: 'status',
        key: 'status',
        render: status => (
          <div>
            <span>
              {status === 'VALID'
                ? '有效'
                : status === 'UNASSIGNED'
                  ? '未配大礼包'
                  : status === 'ASSIGNED'
                    ? '已经分配大礼包'
                    : status === 'RUN_OUT'
                      ? '已经领取完'
                      : '无效'}
            </span>
          </div>
        ),
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        colSpan: this.state.typeVal2 === 'PACKAGE' ? 1 : 2,
        render: (_, record) => {
          return {
            children: (
              <div style={{ textAlign: 'center' }}>
                {record.deleteTime ? null : (
                  <>
                    <a onClick={() => this.editDetail(record)}>
                      <span style={{ wordBreak: 'keep-all' }}>修改 | </span>
                      {/* <Icon type="edit" /> */}
                    </a>
                    {/* <Divider type="vertical" /> */}
                    <Popconfirm
                      title="是否删除该优惠券？"
                      onConfirm={() => this.handleDelete(record.id)}
                    >
                      <a>
                        <span style={{ wordBreak: 'keep-all' }}>删除 | </span>
                        {/* <Icon type="delete" /> */}
                      </a>
                    </Popconfirm>
                    {/* <Divider type="vertical" /> */}
                  </>
                )}
                
                {/* <Tooltip title="查看">
                  <Icon
                    type="eye"
                    onClick={() => router.push(`/coupons/list/ToView?id=${record.id}`)}
                    style={{ cursor: 'pointer', color: '#E83F40' }}
                  />
                </Tooltip> */}
                <span
                  onClick={() => router.push(`/coupons/list/ToView?id=${record.id}`)}
                  style={{ cursor: 'pointer', color: '#E83F40', wordBreak: 'keep-all' }}
                >
                  查看
                </span>
              </div>
            ),
            props: {
              colSpan: this.state.typeVal2 === 'PACKAGE' ? 1 : 2,
            },
          };
        },
      },
    ];
    
    const { isFormModal, current } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <PageHeaderWrapper title="优惠券列表">
        <Card>
          <Spin spinning={false}>
            <Form layout="inline" onSubmit={this.handleSubmit}>
              <Form.Item label="用法">
                {getFieldDecorator(
                  'type',
                  {
                    initialValue: "SINGLE"
                  },
                )(
                  <Select placeholder="用法" onChange={ this.typeChange } style={{ width: 180 }}>
                    <Option value="SINGLE">独立使用</Option>
                    <Option value="PACKAGE">大礼包</Option>
                    {/* <Option value="ACTIVITY">营销活动</Option>
                    <Option value="ALIPAY">支付宝券码券</Option> */}
                  </Select>,
                )}
              </Form.Item>
              <Form.Item label="优惠券名称">
                {getFieldDecorator('title', {})(<Input placeholder="请输入优惠券名称" />)}
              </Form.Item>
              <Form.Item label="优惠券状态">
                {getFieldDecorator(
                  'status',
                  {
                    initialValue: "VALID"
                  },
                )(
                  <Select placeholder="优惠券状态" allowClear style={{ width: 180 }}>
                    <Option value="VALID">有效</Option>
                    <Option value="INVALID">失效</Option>
                    <Option value="RUN_OUT">已经领取完</Option>
                  </Select>,
                )}
              </Form.Item>
              {
                this.state.typeVal === 'PACKAGE'
                  ? (
                    <Form.Item label="是否已分配大礼包">
                      {getFieldDecorator(
                        'hasAssign',
                        {
                          initialValue: "false"
                        },
                      )(
                        <Select placeholder="是否已分配大礼包" style={{ width: 180 }}>
                          <Option value="true">是</Option>
                          <Option value="false">否</Option>
                        </Select>,
                      )}
                    </Form.Item>
                  )
                  : ''
              }
              <div>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                </Form.Item>
                <Form.Item>
                  <Button htmlType="button" onClick={this.handleReset}>
                    重置
                  </Button>
                </Form.Item>
                {/* <Form.Item>
                  <Button>导出</Button>
                </Form.Item> */}
              </div>
            </Form>
            <Button onClick={this.handleAdd} type="primary" style={{ margin: '30px 0' }}>
              新增
            </Button>
            <Table
              scroll={{ x: scroll }}
              onPage={this.onThepage}
              paginationProps={paginationProps}
              expandedRowRender={(record) => this.expandedRowRender(record)}
              dataSource={onTableData(listData)}
              columns={columns}
            />
          </Spin>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default List;
